package com.wechat.api.base;

import com.wechat.api.entity.User;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Liumh on 2018/4/21.
 */
public class BaseProvider<T> {

    private Class clz;
    private Field[] fields;
    private Method[] methods;

    public void insert(T po){

    }

    /**
     * 获取实体参数名称以及参数值
     * @param po
     * @return
     */
    public Map<String, Object> getFieldNameAndValue(T po){
        Map<String, Object> nameAndVal = new HashMap<String, Object>();
        clz = po.getClass();
        fields = clz.getDeclaredFields();
        methods = clz.getMethods();
        for (Field field : fields) {
            String name = field.getName();
            Method method = getMethodByField(name);
            try {
                Object value = method.invoke(po);
                nameAndVal.put(name,value);
            }catch (NullPointerException e){

            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        return nameAndVal;
    }

    /**
     * 通过实体参数名称获取对应get方法
     * @param fieldName
     * @return
     */
    private Method getMethodByField(String fieldName){
        for (Method method : methods) {
            String name = method.getName();
            if (name.substring(3).equalsIgnoreCase(fieldName) &&
                    name.substring(0, 3).equalsIgnoreCase("get")){
                return method;
            }
        }
        return null;
    }

    /**
     * 获取
     * @param type
     */
    private void typeParser(Type type){
        String typeName = type.getTypeName();
        int index = typeName.lastIndexOf(".")+1;
        String fieldType = typeName.substring(index);
        switch (fieldType){
            case "Long":
                System.out.println("Long");
                break;

            case "String":
                System.out.println("String");
                break;

            default:
                System.out.println("default");
                break;
        }
    }


}
